/**
 * 添加flowable扩展
 * @param {*} xmlStr
 * @returns
 */
export function addFlowable(xmlStr:any) {
  const part1 = xmlStr.slice(0, 43); // 从开头到指定位置之前的部分
  const part2 = xmlStr.slice(43); // 从指定位置到末尾的部分
  const newString = part1 + 'xmlns:flowable="http://flowable.org/bpmn" ' + part2; // 拼接成新的字符串
  return removeProp(newString, 'bpmn:sequenceFlow','isDefaultFlow')
}

/**
 * 添加属性信息
 * @param xmlStr
 * @param Elements
 * @param key
 * @param value
 * @returns
 */
export function addProp(xmlStr:string, Elements:string, key:any, value:string) {
  // 创建一个XML文档对象
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(xmlStr, 'application/xml');

  // 查找元素
  const userTaskElement = xmlDoc.getElementsByTagName(Elements);
  for (let i = 0; i < userTaskElement.length; i++) {
    if (!userTaskElement[i].attributes[key]) {
      userTaskElement[i].setAttribute(key, value);
    }
  }

  // 将修改后的XML文档转换回字符串
  const xmlSerializer = new XMLSerializer();
  const modifiedXmlString = xmlSerializer.serializeToString(xmlDoc);

  return modifiedXmlString;
}

/**
 * 删除标签的指定属性信息
 */
export function removeProp(xmlStr:string, Elements:string, key:any) {

  // 创建一个XML文档对象
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(xmlStr, 'application/xml');

  // 查找元素
  const userTaskElement = xmlDoc.getElementsByTagName(Elements);
  // debugger
  for (let i = 0; i < userTaskElement.length; i++) {
    if (userTaskElement[i].attributes[key]) {
      userTaskElement[i].removeAttribute(key);
    }
  }

  // 将修改后的XML文档转换回字符串
  const xmlSerializer = new XMLSerializer();
  const modifiedXmlString = xmlSerializer.serializeToString(xmlDoc);

  return modifiedXmlString;
}

/**
 *根据标签名称返回xml内容，标签名必须唯一，若不满足，修改方法
 * @param {*} xmlStr xml字符串
 * @param {element} tagName 标签名称，如<Name>
 */
export function getTypeNameByTag(xmlStr:string, tagName:string):any {
  const parser = new DOMParser()
  const xmlDoc = parser.parseFromString(xmlStr, 'application/xml')
  const nameNodes = xmlDoc.getElementsByTagName(tagName)[0]
  if (nameNodes) {
    return nameNodes
  } else {
    return false
  }
}

/**
 * 根据标签名称修改内容
 * @param {*} xmlStr xml字符串
 * @param {element} tagName 标签名称，如<Name>
 * @param {*} key 修改对应key
 * @param {*} value 修改值value
 * @returns
 */
export function setValueByTag(xmlStr:string, tagName:string, key:string, value:string) {
  // 字符串转xml
  const parser = new DOMParser()
  const xmlDoc = parser.parseFromString(xmlStr, 'application/xml')
  const nameNodes = xmlDoc.getElementsByTagName(tagName)[0]
  nameNodes.setAttribute(key, value);
  // xml转字符串
  const s = new XMLSerializer();
  const xml = s.serializeToString(xmlDoc);

  return xml;
}
